package com.yoomiito.app.adapter.goods.detail;

import android.content.Context;

import androidx.annotation.NonNull;

import androidx.recyclerview.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.yoomiito.app.R;
import com.yoomiito.app.model.bean.GoodsDetail;
import com.yoomiito.app.model.bean.VideoInfo;
import com.yoomiito.app.ui.video.VideoPlayActivity;
import com.yoomiito.app.utils.AllUtils;
import com.yoomiito.app.utils.BannerImageLoader;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.DateUtils;
import com.yoomiito.app.utils.ImageLoader;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.ResUtil;
import com.yoomiito.app.utils.SpannableUtils;
import com.yoomiito.app.utils.video.MediaPlayerVideoInfo;
import com.yoomiito.app.utils.video.MetadataRetrieverVideoInfo;
import com.yoomiito.app.utils.video.VideoInfoUtil;
import com.yoomiito.app.utils.YMToast;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class GoodsDetailHeaderAdapter extends DelegateAdapter.Adapter<RecyclerView.ViewHolder> {


    private Context mContext;
    private List<GoodsDetail> mGoodsDetails;
    private LayoutHelper mHelper;
    private int mGoodsType;
    //    private int goodsType;
    private OnClickListener mOnClickListener;
    private OnShareClickListener mShareClickListener;

    public GoodsDetailHeaderAdapter(Context context, List<GoodsDetail> mGoodsDetails, LayoutHelper helper) {
        mContext = context;
        this.mGoodsDetails = mGoodsDetails;
        mHelper = helper;
    }

    @Override
    public LayoutHelper onCreateLayoutHelper() {
        return mHelper;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.item_goods_info_header, parent, false);
        return new ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        GoodsDetail goodsDetail = mGoodsDetails.get(position);
        ItemViewHolder viewHolder = (ItemViewHolder) holder;
        if (!TextUtils.isEmpty(goodsDetail.getVideo())) {
            Observable.just(goodsDetail.getVideo())
                    .observeOn(Schedulers.io())
                    .map(s -> {
                        VideoInfoUtil videoInfoUtil;
                        try {
                            videoInfoUtil = new MetadataRetrieverVideoInfo(s);//在vivo手机 系统6.1上会崩溃 这时候就使用MediaPlayerVideoInfo
                        } catch (Exception e) {
                            videoInfoUtil = new MediaPlayerVideoInfo(s);
                        }
                        VideoInfo videoInfo = new VideoInfo();
                        videoInfo.setDuration(videoInfoUtil.getVideoDuration());
                        videoInfo.setWidth(videoInfoUtil.getVideoWidth());
                        videoInfo.setHeight(videoInfoUtil.getVideoHeight());
                        videoInfoUtil.release();
                        return videoInfo;
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(s -> {
//                        L.i("显示时长");
                        viewHolder.mPlayView.setVisibility(View.VISIBLE);
                        viewHolder.mVideoDuration.setText(DateUtils.ms2min(s.getDuration()));
                        s.setUrl(goodsDetail.getVideo());
                        viewHolder.mPlayView.setOnClickListener(v -> VideoPlayActivity.Companion.start(mContext, s));
                    });

        }
        //banner
        if (goodsDetail.getSmall_images() == null || goodsDetail.getSmall_images().getUrls() == null || goodsDetail.getSmall_images().getUrls().size() == 0) {
            setBanner(viewHolder.mBanner, new ArrayList<String>());
        } else {
            setBanner(viewHolder.mBanner, goodsDetail.getSmall_images().getUrls());
        }
        L.i("类型3是" + mGoodsType);
        if (mGoodsType == AllCode.YouPin) {
            if (SpannableUtils.isEmptyOr0(goodsDetail.getDeduction_account())||SpannableUtils.isEmptyOr0(goodsDetail.getUser_deduction_account())) {
                String price = "¥" + SpannableUtils.handlePrice(goodsDetail.getSalePrice());
                viewHolder.mPriceTv.setText(SpannableUtils.getSmallMoneyFlag(price));
            } else {
                String price = "¥" + SpannableUtils.handlePrice(goodsDetail.getCash()) + " 可抵扣¥" + goodsDetail.getDeduction_account();
                int addFlag = price.indexOf(" ");
                SpannableString spanText = new SpannableString(price);
                spanText.setSpan(new RelativeSizeSpan(0.5f), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                spanText.setSpan(new RelativeSizeSpan(0.5f), addFlag, price.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//                spanText.setSpan(new RelativeSizeSpan(0.5f), price.length() - 2, price.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                viewHolder.mPriceTv.setText(spanText);
            }
        } else {
            viewHolder.mPriceTv.setText(mGoodsType == AllCode.TaoBao ?
                    SpannableUtils.getDiscountPrice("¥" + SpannableUtils.handlePrice(goodsDetail.getSalePrice()) + "券后", R.color.color_balk_333333) :
                    (mGoodsType == AllCode.FreeBuyGoods ? (SpannableUtils.getDiscountPrice("¥" + goodsDetail.getSalePrice() + "券后", R.color.color_balk_333333)) :
                            SpannableUtils.getSmallMoneyFlag("¥" + SpannableUtils.handlePrice(goodsDetail.getSalePrice()))));
        }
        //销量
        L.i("销量：" + SpannableUtils.saleNum(goodsDetail.getVolume()));
        viewHolder.mSaleSize.setText((goodsDetail.getGood_type() == 1 ? "月销" : "已售") + SpannableUtils.saleNum(goodsDetail.getVolume()));
        //原价
        switch (mGoodsType) {
            case AllCode.FreeBuyGoods:
            case AllCode.TaoBao:
                viewHolder.mOldPriceTv.setText(SpannableUtils.getSpannable("淘宝原价 " + SpannableUtils.handlePrice(goodsDetail.getZk_final_price()), 4));
                break;
            case AllCode.Gift:
            case AllCode.BaoPin:
            case AllCode.StarStore:
                viewHolder.mOldPriceTv.setText(SpannableUtils.getSpannable("市场价" + SpannableUtils.handlePrice(goodsDetail.getReserve_price()), 3));
                if (SpannableUtils.isEmptyOr0(goodsDetail.getReserve_price())) {
                    viewHolder.mOldPriceTv.setVisibility(View.GONE);
                }
                break;
            case AllCode.YouPin:
//            case AllCode.AgentMall:
//                if (SpannableUtils.isEmptyOr0(goodsDetail.getReserve_price())) {
//                    viewHolder.mOldPriceTv.setVisibility(View.GONE);
//                } else {
                if (goodsDetail.getYo_money_not() == 0) {
                    viewHolder.mOldPriceTv.setText(SpannableUtils.getSpannable("市场价¥" + SpannableUtils.handlePrice(goodsDetail.getReserve_price()), 3));
                    if (SpannableUtils.isEmptyOr0(goodsDetail.getReserve_price())) {
                        viewHolder.mOldPriceTv.setVisibility(View.GONE);
                    }
                } else {
                    viewHolder.mOldPriceTv.setText("原价 ¥" + SpannableUtils.handlePrice(goodsDetail.getSalePrice()));
                }
//                }
                break;
        }
        //标题
        viewHolder.mTitileTv.setText(goodsDetail.getTitle());
        viewHolder.mTitileTv.setOnLongClickListener(v -> {
            AllUtils.copyText(viewHolder.mTitileTv.getContext(), viewHolder.mTitileTv.getText().toString().trim());
            YMToast.showText("复制成功");
            return false;
        });
        //优惠信息
        viewHolder.mCouponRule.setText(goodsDetail.getCoupon_info());
        viewHolder.mCouponRule.setText("无门槛");
        if (AllCode.FreeBuyGoods == mGoodsType) {
            viewHolder.mShareTv.setVisibility(View.GONE);
        }
        //分享
        viewHolder.mShareTv.setOnClickListener(v -> {
            if (mShareClickListener != null) {
                mShareClickListener.onClick();
            }
        });

        //usertype 0 淘宝 1 天猫
        if (AllCode.TaoBao == mGoodsType || AllCode.FreeBuyGoods == mGoodsType) {
            switch (goodsDetail.getUser_type()) {
                case 0:
                    viewHolder.mIcon.setImageResource(R.mipmap.tb);
                    viewHolder.mStoreFlag.setImageResource(R.drawable.taobao_big);
                    break;
                case 1:
                    viewHolder.mIcon.setImageResource(R.mipmap.tmall);
                    viewHolder.mStoreFlag.setImageResource(R.drawable.tmall_big);
                    break;
            }
            //店铺logo
            ImageLoader.getInstance().into(mContext, goodsDetail.getShop_logo().getPict_url(), viewHolder.mStoreLogo, R.drawable.default_shop_logo);
            //店铺名称
            viewHolder.mStoreNameTv.setText(goodsDetail.getNick().replace(" ", "\n"));
            //优惠券
//            if (TextUtils.isEmpty(goodsDetail.getCoupon_price())
//                    || "0".equals(goodsDetail.getCoupon_price())
//                    || "0.0".equals(goodsDetail.getCoupon_price())
//                    || "0.00".equals(goodsDetail.getCoupon_price())
//            ) {
            if (AllCode.FreeBuyGoods == mGoodsType || SpannableUtils.isEmptyOr0(goodsDetail.getCoupon_price())) {
                viewHolder.mCouponView.setVisibility(View.GONE);
                return;
            }
            //63  56  43
            viewHolder.mCouponMoneyTv.setText(SpannableUtils.handlePrice(goodsDetail.getCoupon_price()));
            viewHolder.mCouponMoneyTv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, getTextSize(goodsDetail.getCoupon_price()));
            viewHolder.mCouponDate.setText("使用期限：" + goodsDetail.getCoupon_start_time().replaceAll("-", ".")
                    + "-"
                    + goodsDetail.getCoupon_end_time().replaceAll("-", "."));
            viewHolder.mCouponBtn.setOnClickListener(v -> {
                if (mOnClickListener != null) {
                    mOnClickListener.onClick(goodsDetail.getCoupon_click_url());
                }
            });
        } else {
            viewHolder.mIcon.setVisibility(View.GONE);
            viewHolder.mCouponView.setVisibility(View.GONE);
            viewHolder.mStoreView.setVisibility(View.GONE);
            viewHolder.mFlowlayout.setVisibility(View.VISIBLE);
            List<String> s = new ArrayList<>();
            if (!TextUtils.isEmpty(goodsDetail.getProductPoint())) {
                s.add(goodsDetail.getProductPoint());
            }
            viewHolder.mFlowlayout.setAdapter(new TagAdapter<String>(s) {
                @Override
                public View getView(FlowLayout parent, int position, String s) {
                    TextView tv = (TextView) LayoutInflater.from(mContext).inflate(R.layout.item_goods_flag, parent, false);
                    tv.setTextColor(ResUtil.getColor(R.color.color_ff5100));
                    tv.setBackgroundResource(R.drawable.goods_flag);
                    tv.setText(s);
                    return tv;
                }
            });
        }
        L.i("刷新完成");
    }

    @Override
    public int getItemCount() {
        return mGoodsDetails.size();
    }

    @Override
    public int getItemViewType(int position) {
        return 1;
    }

    private void setBanner(Banner banner, List<String> images) {
        //设置banner样式
        banner.setBannerStyle(BannerConfig.NUM_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new BannerImageLoader());
        //设置图片集合
        banner.setImages(images);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(2500);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
        banner.setFocusable(false);
        banner.setFocusableInTouchMode(false);

    }


    public void setGoodsType(int goodsType) {
        this.mGoodsType = goodsType;
    }

    private int getTextSize(String s) {
        switch (s.length()) {
            case 1:
            case 2:
                return 63;
            case 3:
                return 56;
            case 4:
                return 43;
        }
        return 30;

    }

    private class ItemViewHolder extends RecyclerView.ViewHolder {

        private TagFlowLayout mFlowlayout;
        private View mStoreView;
        private TextView mCouponRule;
        private TextView mStoreCoupon;
        private ImageView mStoreFlag;
        private ImageView mStoreLogo;
        private TextView mCouponDate;
//        private ImageView mBackIv;
        private ImageView mCouponBtn;
        private TextView mCouponMoneyTv;
        private View mCouponView;
        private ImageView mIcon;
        private TextView mSaleSize;
        private Banner mBanner;
        private TextView mPriceTv;
        private TextView mOldPriceTv;
        private TextView mTitileTv;
        private TextView mShareTv;
        private TextView mStoreNameTv;
        private LinearLayout mPlayView;
        private TextView mVideoDuration;
//        private View mSaleTv;

        public ItemViewHolder(View itemView) {
            super(itemView);
            mBanner = itemView.findViewById(R.id.goods_header_banner);
//            mBackIv = itemView.findViewById(R.id.goods_header_back);
//            mBackIv.setOnClickListener(v -> (
//                    (GoodsInfoActivity) mContext).finish()
//            );
            mPriceTv = itemView.findViewById(R.id.goods_price);
            mSaleSize = itemView.findViewById(R.id.goods_header_sale_size);
            mOldPriceTv = itemView.findViewById(R.id.goods_old_price);
//            mSaleTv = itemView.findViewById(R.id.goods_header_tv_1);
            mIcon = itemView.findViewById(R.id.goods_header_icon);
            mTitileTv = itemView.findViewById(R.id.goods_header_title);
            mShareTv = itemView.findViewById(R.id.goods_header_share);
            mCouponView = itemView.findViewById(R.id.item_coupon_view);
            mCouponMoneyTv = itemView.findViewById(R.id.item_coupon_money);
            mCouponBtn = itemView.findViewById(R.id.item_coupon_btn);
            mCouponDate = itemView.findViewById(R.id.item_coupon_date);
            mStoreView = itemView.findViewById(R.id.item_store_view);
            mStoreLogo = itemView.findViewById(R.id.item_store_logo);
            mStoreNameTv = itemView.findViewById(R.id.item_store_name);
            mStoreFlag = itemView.findViewById(R.id.item_store_flag);
            mStoreCoupon = itemView.findViewById(R.id.item_store_all_coupon);
            mCouponRule = itemView.findViewById(R.id.item_coupon_rule);
            mFlowlayout = itemView.findViewById(R.id.item_goods_info_header_flowLayout);
            mPlayView = itemView.findViewById(R.id.playVideoView);
            mVideoDuration = itemView.findViewById(R.id.durationTv);
        }
    }

    public void setOnClickListener(OnClickListener onClickListener) {
        mOnClickListener = onClickListener;
    }

    public void setShareClickListener(OnShareClickListener shareClickListener) {
        mShareClickListener = shareClickListener;
    }


    public interface OnClickListener {
        void onClick(String s);
    }

    public interface OnShareClickListener {
        void onClick();
    }

}
